<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="searchDeviceForm" :model="searchDeviceForm" label-width="80px">
        <el-col :span="5">
          <el-form-item style="margin-bottom: 5px;" label="设备号">
            <el-input v-model="searchDeviceForm.number" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item style="margin-bottom: 5px;" label="标签名">
            <el-input v-model="searchDeviceForm.tag" />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-button style="margin-left:20px" type="primary" @click="searchPage">搜索</el-button>
          <el-button style="float:right;" type="primary" @click="handleAddDevice">添加设备</el-button>
        </el-col>
      </el-form>
    </div>
    <div class="table-container" :style="{width:'100%',height:Height,overflow:'auto'}">
      <el-table
        v-loading="listLoading"
        :data="deviceList"
        style="width: 100%;min-width: 800px;margin-top:10px;"
        border
      >
        <el-table-column align="center" label="设备ID" width="100">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="设备号" width="100">
          <template slot-scope="scope">
            {{ scope.row.number }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="设备名" width="150">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="设备标签" width="150">
          <template slot-scope="scope">
            {{ scope.row.tag ? scope.row.tag : '无' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="报警状态" width="150">
          <template slot-scope="scope">
            <div :style="getAlarmStyle(scope.row)" />
            {{ getAlarmName(scope.row.alarmLevel, scope.row) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="在线状态" width="100">
          <template slot-scope="scope">
            {{ getOnline(scope.row.online) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="开关" width="150">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              style="display: block"
              active-color="#13ce66"
              inactive-color="#3283CB"
              @change="handleSwitch(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="160" min-width="150">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleUpdateDevice(scope)">修改</el-button>
            <el-button type="danger" size="small" @click="handleDeleteDevice(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :visible.sync="dialogVisible"
        :title="dialogType==='edit'?'更新设备信息':'添加设备信息'"
      >
        <el-form
          ref="deviceForm"
          :model="deviceForm"
          :rules="rules"
          class="add-device-container"
        >
          <el-form-item label="设备号" prop="number">
            <el-input v-model="deviceForm.number" type="text" placeholder="请输入设备号" />
          </el-form-item>
          <el-form-item label="设备名" prop="name">
            <el-input v-model="deviceForm.name" type="text" placeholder="请输入设备名" />
          </el-form-item>
          <el-form-item label="设备标签" prop="tag">
            <el-row>
              <el-col :span="8">
                <el-input v-model="tmpTag" type="text" />
              </el-col>
              <el-col :span="8">
                <el-button @click="addTag">添加标签</el-button>
              </el-col>
            </el-row>
            <template v-for="(tag,idx) in tags" v-bind="idx">
              <span :key="idx" style="margin-left:2px;cursor:pointer;display:inline-block" @click="removeTag(idx)">{{ tag }}&emsp;</span>
            </template>
          </el-form-item>
          <el-form-item label="设备简介" prop="desc">
            <el-input
              v-model="deviceForm.desc"
              type="textarea"
              placeholder="设备简介"
              :autosize="{ minRows: 4, maxRows: 4 }"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
          <div style="text-align:right;">
            <el-button v-loading="loading" type="danger" @click="dialogVisible=false">取消</el-button>
            <el-button v-loading="loading" type="primary" @click="confirm">确认</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
    <div class="page-container">
      <el-pagination
        :current-page="devicePage.page"
        :page-size="devicePage.pageSize"
        :page-count="devicePage.pages"
        :total="devicePage.counts"
        :pager-count="devicePage.pageCount"
        align="center"
        layout="prev, pager, next, jumper"
        @current-change="handlePageChange"
        @prev-click="handlePageChange"
        @next-click="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import { addDevice, delDevice, updateDevice } from '@/api/device'
import { findPage, setStatus, setTag } from '@/api/device-status'

const defaultDevicePage = {
  page: 1,
  pageSize: 10,
  pageCount: 9
}
const defaultDeviceForm = {
  number: '',
  name: '',
  tag: '',
  desc: ''
}
export default {
  name: 'MyDevice',
  data() {
    return {
      Height: '',
      loading: false,
      tags: [],
      tmpTag: '',
      searchDeviceForm: { tag: '', number: '' },
      devicePage: Object.assign({}, defaultDevicePage),
      deviceForm: Object.assign({}, defaultDeviceForm),
      deviceList: [],
      dialogVisible: false,
      dialogType: 'new',
      listLoading: true,
      rules: {
        number: [{ required: true, message: '请输入设备号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入设备名', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入设备简介', trigger: 'blur' }]
      }
    }
  },
  watch: {
    'tags': {
      handler(newVal) {
        console.log('new-tags', newVal)
      }
    },
    '$route.query': {
      handler(newVal, oldVal) {
        const query = this.$route.query
        if (Object.keys(newVal).length !== Object.keys(oldVal).length || (
          newVal.tag !== oldVal.tag || newVal.number !== oldVal.number
        )) {
          newVal.page = 1
          newVal.pageSize = 10
        }
        if (query.number) this.searchDeviceForm.number = query.number
        if (query.tag) this.searchDeviceForm.tag = query.tag
        findPage(query).then(response => {
          this.updatePage(response.data.pager)
        })
      },
      deep: true
    }
  },
  created() { // 获取屏幕高度
    const screenHeight = document.documentElement.clientHeight - 200 + 'px'
    this.$nextTick(() => {
      this.Height = screenHeight
    })
    const query = this.$route.query
    let data = {}
    if (query) {
      if (query.page) data.page = parseInt(query.page)
      if (query.pageSize) data.pageSize = parseInt(query.pageSize)
      if (query.number) data.number = this.searchDeviceForm.number = query.number
      if (query.tag) data.tag = this.searchDeviceForm.tag = query.tag
    } else {
      data = { page: 1, pageSize: 10 }
    }
    findPage(data).then(response => {
      this.updatePage(response.data.pager)
    })
  },
  mounted() {
    document.getElementsByClassName('el-pagination__jump')[0].childNodes[0].nodeValue = '跳转第'
    document.getElementsByClassName('el-pagination__jump')[0].insertAdjacentText('beforeend', '页')
    window.onresize = () => {
      return (() => {
        this.Height = document.documentElement.clientHeight - 200 + 'px'
      })()
    }
  },
  methods: {
    simplify(obj) {
      const res = Object.assign({}, obj)
      for (const key of Object.keys(res)) {
        if (res[key] === '') delete res[key]
      }
      return res
    },
    searchPage() {
      let data = Object.assign({}, this.searchDeviceForm)
      data = Object.assign(data, this.devicePage)
      delete data['counts']
      this.$router.replace({
        path: this.$route.path,
        query: this.simplify(data)
      })
    },
    updatePage(pager) {
      this.devicePage = {
        page: pager.page,
        pages: pager.pages,
        pageSize: pager.pageSize,
        counts: pager.counts
      }
      this.deviceList = pager.items
      this.listLoading = false
    },
    handlePageChange(param) {
      this.devicePage.page = param
      const data = Object.assign({}, this.devicePage)
      delete data['counts']
      if (this.searchDeviceForm.number) data.number = this.searchDeviceForm.number
      if (this.searchDeviceForm.tag) data.tag = this.searchDeviceForm.tag
      this.$router.replace({
        path: this.$route.path,
        query: this.simplify(data)
      })
    },
    getTags(tag) {
      console.log('tag', tag)
    },
    getStateColor(alarmLevel) {
      if (alarmLevel === 0) return '#9ee33b'
      if (alarmLevel < 3) return '#3BA1DE'
      if (alarmLevel < 5) return '#E1A128'
      if (alarmLevel < 8) return '#E32B3C'
    },
    getAlarmStyle(row) {
      return {
        display: 'inline-block',
        marginLeft: '20px',
        width: '15px',
        height: '15px',
        borderRadius: '10px',
        backgroundColor: this.getStateColor(row.alarmLevel)
      }
    },
    getAlarmName(alarmLevel, row) {
      if (alarmLevel === 0) return '正常'
      else return row.alarmName
    },
    getOnline(online) {
      if (online) return '在线'
      else return '离线'
    },
    handleSwitch(row) {
      console.log('switch', row)
      setStatus(row).then(response => {
        console.log('resp', response)
      })
    },
    updateDevice() {
      this.$refs.deviceForm.validate(valid => {
        if (valid) {
          this.loading = true
          console.log('deviceForm', this.deviceForm)
          setTag(this.deviceForm)
          updateDevice(this.deviceForm)
          this.loading = false
        } else {
          console.log('error update!!')
          return false
        }
      })
    },
    handleAddDevice() {
      this.dialogType = 'new'
      this.deviceForm = Object.assign({}, defaultDeviceForm)
      this.dialogVisible = true
    },
    handleUpdateDevice(scope) {
      this.dialogType = 'edit'
      if (scope.row.tag) this.tags = scope.row.tag.split(',')
      console.log('tag', scope.row.tag, this.tags)
      this.deviceForm = {
        number: scope.row.number,
        name: scope.row.name,
        desc: scope.row.description
      }
      this.dialogVisible = true
    },
    handleDeleteDevice({ $index, row }) {
      this.$confirm('是否移除该设备?', 'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delDevice({ number: row.number })
        console.log('$index', $index)
        this.deviceList.splice($index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(err => {
        console.error(err)
      })
    },
    async confirm() {
      const isEdit = this.dialogType === 'edit'
      this.deviceForm.tag = this.tags.join(',')
      if (!isEdit) {
        await addDevice(this.deviceForm).then((response) => {
          this.deviceForm = response.data.device
          this.deviceList.push(this.deviceForm)
        })
      } else {
        await this.updateDevice()
        for (let index = 0; index < this.deviceList.length; index++) {
          if (this.deviceList[index].number === this.deviceForm.number) {
            this.deviceList[index].name = this.deviceForm.name
            this.deviceList[index].tag = this.deviceForm.tag
            this.deviceList[index].description = this.deviceForm.desc
            break
          }
        }
      }
      const { number, name, desc } = this.deviceForm
      this.dialogVisible = false
      this.$notify({
        title: '操作成功',
        dangerouslyUseHTMLString: true,
        message: `
            <div>设备号: ${number}</div>
            <div>设备名: ${name}</div>
            <div>设备简介: ${desc}</div>
          `,
        type: 'success'
      })
    },
    addTag() {
      if (this.tmpTag) {
        const excludeChar = "!@#$%^&*()_+{}|:\"<>?[]\\;\',./"
        for (const ch of excludeChar) {
          if (this.tmpTag.indexOf(ch) >= 0) {
            this.$message.error('不能包括特殊字符')
            this.tmpTag = ''
            return
          }
        }
        if (this.tags.indexOf(this.tmpTag) >= 0) {
          this.$message.error('标签已存在')
        } else this.tags.push(this.tmpTag)
      } else this.$message.error('标签不能为空')
      this.tmpTag = ''
    },
    removeTag(idx) {
      this.tags.splice(idx, 1)
    }
  }
}
</script>

<style scoped>

.search-container {
  width: 100%;
  height: 50px;
}

.table-container {
  width: 100%;
}

.page-container {
  width: 100%;
}
</style>
